package com.ark.common.utils;

import com.ark.common.constant.HttpStatus;
import com.ark.common.domain.model.LoginUser;
import com.ark.common.exception.ServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class SecurityUtils {

    private static final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 用户ID
     **/
    public static Long getUserId()
    {
        try
        {
            return getLoginUser().getUserId();
        }
        catch (Exception e)
        {
            throw new ServiceException(HttpStatus.UNAUTHORIZED,"获取用户ID异常");
        }
    }

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser()
    {
        try
        {
            return (LoginUser) getAuthentication().getPrincipal();
        }
        catch (Exception e)
        {
            throw new ServiceException(HttpStatus.UNAUTHORIZED,"获取用户信息异常");
        }
    }


    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication()
    {
        return SecurityContextHolder.getContext().getAuthentication();
    }


    public static boolean isAdmin(Long userId)
    {
        return userId != null && 1L == userId;
    }

    /**
     * 加密
     * @param password 密码
     */
    public static String encrypt(String password){
       return passwordEncoder.encode(password);
    }

    /**
     * 验证密码
     * @param rawPassword     密码
     * @param encodedPassword 加密密码
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword)
    {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }
}
